package com.walala.logic.server;

import com.walala.logic.common.Constant;
import com.walala.logic.protocol.ProtocolPackage;
import com.walala.logic.utils.ProtoMessageUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class LogicProtocolEncoder extends MessageToMessageEncoder<ProtocolPackage> {

	private Logger logger = LoggerFactory.getLogger(LogicProtocolEncoder.class);

	@Override
	protected void encode(ChannelHandlerContext ctx, ProtocolPackage msg, List<Object> out) throws Exception {
		logger.info("[encode] start,cmd:[{}],traceId:[{}]",msg.getCommand(),msg.getTraceId());
		ByteBuf buf = Unpooled.buffer();
		buf.writeByte(Constant.pack_start_tag);
		byte[] head = ProtoMessageUtil.encodeHead(msg);
		buf.writeBytes(head);
		if(msg.getProtoBody() != null) {
			buf.writeBytes(msg.getProtoBody());
		}
		buf.writeByte(Constant.pack_end_tag);
		out.add(buf);
		logger.info("[encode] end,cmd:[{}],traceId:[{}]",msg.getCommand(),msg.getTraceId());
	}

}
